package org.xbzheng.restful_study.dao;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.xbzheng.restful_study.model.Room;
import org.xbzheng.restful_study.model.RoomColumn;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by Administrator on 2016/11/1.
 */
@Repository

public class RoomDao {

    @PersistenceContext
    private EntityManager entityManager;

    public Room save(final Room room){
        return entityManager.merge(room);
    }

    public RoomColumn save(final RoomColumn roomColumn){
        return entityManager.merge(roomColumn);
    }

    public Room findByName(final String roomName){
        final Query query = entityManager.createQuery("select r from Room r where r.roomName=?1");
        query.setParameter(1, roomName);

        final List<Room> rooms = query.getResultList();

        return rooms.isEmpty()? null : rooms.get(0);
    }

    public Room findById(final int roomId){
        return entityManager.find(Room.class, roomId);
    }

    public List<Room> findRooms(){
        return entityManager.createQuery("select r from Room r ").getResultList();
    }
}
